//
//  NetworkingTools.swift
//  weibo
//
//  Created by David on 15/11/24.
//  Copyright © 2015年 DV. All rights reserved.
//

import UIKit
import AFNetworking
import ReactiveCocoa
class NetworkingTools: AFHTTPSessionManager {
    private var clientId = "2075091997"
    private var appSecret = "642b34937e0893e3b170a2c13a77a3e4"
     var redirectUri = "http://www.baidu.com"
    
    enum requireMethod : String {
        case get = "GET"
        case post = "POST"
    }
    
    static let sharedTools : NetworkingTools = {
        let instance : NetworkingTools = NetworkingTools(baseURL: nil)
        
        instance.responseSerializer.acceptableContentTypes?.insert("text/html")
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return instance
    }()
    
    func request( method : requireMethod,urlString : String,param : [String : AnyObject])->RACSignal{
        return RACSignal.createSignal({ (subscriber) -> RACDisposable! in
            let successCallBack = { (task : NSURLSessionDataTask , result : AnyObject) in
                
                subscriber.sendNext(result)
                subscriber.sendCompleted()
            }
            let failureCallBack = { (task : NSURLSessionDataTask?,error:NSError) -> Void in
                subscriber.sendError(error)
            
            }
            switch method{
            case .get:
                self.GET(urlString, parameters: param, success: successCallBack, failure:failureCallBack)
            case .post:
                self.POST(urlString, parameters: param, success: successCallBack, failure: failureCallBack)
            }

            
            return nil
        })
        
    }
    
     var authURL : NSURL  {
        let url =  "https://api.weibo.com/oauth2/authorize?client_id=\(clientId)&redirect_uri=\(redirectUri)"
        
        return NSURL(string: url)!
    }
    
    func loadAccessToken(code : String)->RACSignal{
        let urlstring = "https://api.weibo.com/oauth2/access_token"

        let param = ["client_id": clientId,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri]
        //提交 参数 用post
       return request(.post, urlString: urlstring, param: param)
    }
    func loadUserInfo(accesstoken:String,uid:String)->RACSignal{
        let urlString = "https://api.weibo.com/2/users/show.json"
        let param = ["access_token":accesstoken,"uid":uid]
        
        return request(.get, urlString: urlString, param: param)
    }
    

}
